package cn.aj.pro.controller;

import cn.aj.pro.service.IProductService;
import cn.aj.pro.domain.Product;
import cn.aj.pro.query.ProductQuery;
import cn.aj.basic.utils.AjaxResultUtil;
import cn.aj.basic.utils.PageListUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    public IProductService productService;


    /**
     * 保存和修改公用的
     * @param product  传递的实体
     * @return AjaxResult转换结果
     */
    @PutMapping
    public AjaxResultUtil addOrUpdate(@RequestBody Product product){
        try {
            if( product.getId()!=null)
                productService.update(product);
            else
                productService.add(product);
            return AjaxResultUtil.getAjaxResult().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResultUtil.getAjaxResult().fail();
        }
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResultUtil delete(@PathVariable("id") Long id){
        try {
            productService.delete(id);
            return AjaxResultUtil.getAjaxResult().success();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResultUtil.getAjaxResult().fail();
        }
    }
	
    //获取用户
    @GetMapping("/{id}")
    public Product get(@PathVariable("id")Long id)
    {
        return productService.getById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    public List<Product> list(){

        return productService.loadAll();
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public PageListUtil<Product> json(@RequestBody ProductQuery query)
    {
        return productService.loadPage(query);
    }

    /**
    * @Title: productOnsale
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2022/12/9 0009 10:07
    * @Parameters: [ids]
    * @Return cn.aj.basic.utils.AjaxResultUtil
     * 产品上架
    */
    @PostMapping("/onsale")
    public AjaxResultUtil productOnsale(@RequestBody List<Long> ids)
    {
        productService.productOnsale(ids);
        return AjaxResultUtil.getAjaxResult().success();
    }

    /**
    * @Title: productOffsale
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2022/12/9 0009 10:30
    * @Parameters: [ids]
    * @Return cn.aj.basic.utils.AjaxResultUtil
     * 产品下架
    */
    @PostMapping("/offsale")
    public AjaxResultUtil productOffsale(@RequestBody List<Long> ids)
    {
        productService.productOffsale(ids);
        return AjaxResultUtil.getAjaxResult().success();
    }
}
